'use client'

import { useState, useEffect } from 'react'
import DashboardLayout from '@/components/layouts/DashboardLayout'
import AddDeviceModal from '@/components/devices/AddDeviceModal'
import DeviceCard from '@/components/devices/DeviceCard'
import { toast } from 'react-hot-toast'

interface Device {
  id: string
  name: string
  type: string
  status: boolean
  data: {
    power?: number
    temperature?: number
    brightness?: number
    position?: number
  }
}

export default function DevicesPage() {
  const [devices, setDevices] = useState<Device[]>([])
  const [isAddModalOpen, setIsAddModalOpen] = useState(false)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    fetchDevices()
  }, [])

  const fetchDevices = async () => {
    try {
      const res = await fetch('/api/devices')
      const data = await res.json()
      
      if (!res.ok) {
        throw new Error(data.error || '获取设备列表失败')
      }

      console.log('获取到的设备列表:', data) // 调试日志
      setDevices(data)
    } catch (error) {
      setError('获取设备列表失败')
      console.error(error)
      toast.error('获取设备列表失败')
    } finally {
      setLoading(false)
    }
  }

  const handleAddDevice = async (deviceData: Omit<Device, 'id'>) => {
    try {
      console.log('添加设备数据:', deviceData) // 调试日志

      const res = await fetch('/api/devices', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(deviceData),
      })

      const data = await res.json()
      
      if (!res.ok) {
        throw new Error(data.error || '添加设备失败')
      }

      console.log('设备创建成功:', data) // 调试日志
      setDevices(prev => [...prev, data])
      setIsAddModalOpen(false)
      toast.success('添加设备成功')
    } catch (error) {
      console.error('添加设备失败:', error)
      toast.error(error instanceof Error ? error.message : '添加设备失败')
    }
  }

  const handleToggleDevice = async (id: string) => {
    try {
      const device = devices.find(d => d.id === id)
      if (!device) return

      const res = await fetch(`/api/devices/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          status: !device.status
        }),
      })

      if (!res.ok) throw new Error('更新设备状态失败')
      
      setDevices(prev =>
        prev.map(device =>
          device.id === id
            ? { ...device, status: !device.status }
            : device
        )
      )
    } catch (error) {
      console.error('切换设备状态失败:', error)
    }
  }

  const handleUpdateDeviceData = async (id: string, data: Record<string, number>) => {
    try {
      const res = await fetch(`/api/devices/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ data }),
      })

      if (!res.ok) throw new Error('更新设备数据失败')

      setDevices(prev =>
        prev.map(device =>
          device.id === id
            ? {
                ...device,
                data: { ...device.data, ...data }
              }
            : device
        )
      )
    } catch (error) {
      console.error('更新设备数据失败:', error)
    }
  }

  const handleDeleteDevice = async (id: string) => {
    try {
      const res = await fetch(`/api/devices/${id}`, {
        method: 'DELETE',
      })

      if (!res.ok) throw new Error('删除设备失败')
      setDevices(prev => prev.filter(device => device.id !== id))
    } catch (error) {
      console.error('删除设备失败:', error)
    }
  }

  if (loading) {
    return (
      <DashboardLayout>
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-500"></div>
        </div>
      </DashboardLayout>
    )
  }

  if (error) {
    return (
      <DashboardLayout>
        <div className="flex flex-col items-center justify-center h-64">
          <div className="text-red-400 mb-4">{error}</div>
          <button
            onClick={fetchDevices}
            className="btn btn-primary"
          >
            重试
          </button>
        </div>
      </DashboardLayout>
    )
  }

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <h1 className="text-3xl font-bold text-white/90">设备管理</h1>
          <button
            onClick={() => setIsAddModalOpen(true)}
            className="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition-colors"
          >
            添加设备
          </button>
        </div>

        {devices.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-white/60">暂无设备</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {devices.map(device => (
              <DeviceCard
                key={device.id}
                device={device}
                onToggle={() => handleToggleDevice(device.id)}
                onDelete={() => handleDeleteDevice(device.id)}
                onUpdateData={(data) => handleUpdateDeviceData(device.id, data)}
              />
            ))}
          </div>
        )}

        <AddDeviceModal
          isOpen={isAddModalOpen}
          onClose={() => setIsAddModalOpen(false)}
          onAdd={handleAddDevice}
        />
      </div>
    </DashboardLayout>
  )
} 